using System.Data;
using System.Text;

public class JsonSerializer {
    public static string Serialize(DataTable table) {
        StringBuilder json = new StringBuilder();
        json.Append("[");
        for (int i = 0; i < table.Rows.Count; i++) {
            DataRow row = table.Rows[i];

            // json object
            json.Append("{");
            for (int j = 0; j < table.Columns.Count; j++) {
                string columnName = table.Columns[j].ColumnName;
                string columnType = table.Columns[j].DataType.Name;

                // json field
                if (columnType == "Int32" || columnType == "Int16" || columnType == "Decimal") {
                    // don't surround numbers with quotes
                    json.AppendFormat("\"{0}\":\"{1}\"", columnName, row.IsNull(columnName) ? "" : row[columnName]);
                } else if (columnType == "Boolean") {
                    // make the bool value lowercase
                    json.AppendFormat("\"{0}\":{1}", columnName, row.IsNull(columnName) ? "" : row[columnName].ToString().ToLower());
                } else {
                    // everything else gets quotes around the data
                    json.AppendFormat("\"{0}\":\"{1}\"", columnName, row[columnName]);
                }

                if (j < table.Columns.Count - 1) json.Append(","); // add comma if not last column
            }
            json.Append("}");

            if (i < table.Rows.Count - 1) json.Append(","); // add comma if not last row
        }
        json.Append("]");
        return json.ToString();
    }
}